<template>
  <div class="content">
    <h1>电影后台管理系统</h1>
    <div class="login_box">
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userLogin">登录</el-button>
          <div>
            <span style="color: gray; cursor: pointer">
              <a href="/register">去注册</a>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      account: [{ username: 'admin', password: '123456' }],
      form: {
        username: 'admin',
        password: '123456',
      },
      rules: {
        username: [
          { required: true, message: '请填写登录账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请填写登录密码', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    ...mapMutations('user', ['saveInfo']),
    userLogin() {
      this.$refs.form.validate().then(res => {
        if (res) {
          const account = JSON.parse(localStorage.getItem('account'));
          var flag = false;
          flag = account.some(item => item.username === this.form.username);
          if (flag === true) {
            account.forEach((item, index) => {
              if (
                item.username === this.form.username &&
                item.password === this.form.password
              ) {
                localStorage.setItem(
                  'userInfo',
                  JSON.stringify(account[index])
                );
                this.saveInfo();
              }
            });
          } else {
            this.$message.error('账号不存在');
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  height: 100vh;
  background-color: #545c64;
  overflow-y: hidden;
  h1 {
    text-align: center;
    color: #fff;
    margin-top: 30px;
  }
  .login_box {
    width: 400px;
    padding: 16px;
    margin: 100px auto;
    border-radius: 10px;
    background-color: #fff;
  }
}
</style>
